from flask import Blueprint, request, session, current_app
from models.starlist import StarListModel
from utils import restful
from exts import db
from datetime import datetime
from hooks import login_auth

bp = Blueprint('starlist', __name__, url_prefix='/starlist')


# 1、修改starList
@bp.route('/update', methods=['POST', 'PUT'])
@login_auth
def update_starlist():
    data = request.json
    user_id = session.get('open_id')
    blog_id = data.get('blog_id')
    if user_id and blog_id:
        sl = StarListModel.query\
            .filter(StarListModel.star_user_id == user_id, StarListModel.star_blog_id == blog_id)\
            .one_or_none()
        if sl:  # 删除
            db.session.delete(sl)
            db.session.commit()
        else:  # 新增
            sl = StarListModel(star_user_id=user_id, star_blog_id=blog_id)
            db.session.add(sl)
            db.session.commit()
    else:
        return restful.params_error()
    return restful.ok(message='修改成功')


# 2、获取starlist、blogs
@bp.route('/get/<int:last_time>', methods=['GET'])
@login_auth
def get_starlist_blog(last_time):
    open_id = session.get('open_id')
    res = []
    page_size = current_app.config['STARLIST_PAGE_SIZE']
    last_time = datetime.fromtimestamp(last_time//1000)
    if open_id:
        query = StarListModel.query\
            .filter(StarListModel.star_user_id == open_id, StarListModel.create_date < last_time)\
            .order_by(StarListModel.create_date.desc())
        sts = query.limit(page_size).all()
        for s in sts:
            tmp = s.blog.to_dict(choice='simple')
            tmp['create_date'] = s.create_date.timestamp() * 1000
            res.append(tmp)
    else:
        return restful.unlogin_error()
    return restful.ok(data={'blogs': res})



